package com.asiainfo.util.springmvc;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * spring中日期转换
 * 
 * <pre>
 * &#064;InitBinder
 * public void initBinder(WebDataBinder binder) {
 * 	binder.registerCustomEditor(Date.class, new DateConvertEditor());
 * 	// binder.registerCustomEditor(Date.class, new
 * 	// DateConvertEditor(&quot;yyyy-MM-dd&quot;));
 * 	binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
 * }
 * </pre>
 * @author luhf
 * @date 2013-1-13 下午10:24:33
 */
public class DateConvertEditor extends PropertyEditorSupport{
	
	private static final Logger log=LoggerFactory.getLogger(DateConvertEditor.class);

	static{
		log.debug("启动DateConvertEditor工具类!");
	}

	/**
	 * 私用构造主法.因为此类是工具类.
	 */
	public DateConvertEditor(){
		super();
		this.format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	}
	
	private DateFormat format;
	
	public DateConvertEditor(String format) {
		this.format = new SimpleDateFormat(format);
	}

	/** Date -> String */
	@Override
	public String getAsText() {
		if (getValue() == null)
			return "";
		return this.format.format(getValue());
	}

	/** String -> Date */
	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		if (!StringUtils.isNotBlank(text)) {
			setValue(null);
		} else {
			try {
				setValue(this.format.parse(text));
			} catch (ParseException e) {
				throw new IllegalArgumentException("不能被转换的日期字符串，请检查!", e);
			}
		}
	}
	
	public static void main(String[] args){
		new DateConvertEditor();
	}
}
